const express = require('express');
const app = express();
// 加密信息
const Secret = 'Bearer '
const bcryptjs = require('bcryptjs')//引入加/解密 js包  需要按需使用
//引入生成token包
const jwt = require('jsonwebtoken'); 
const port = 3000;

app.use(express.json())

const { users } =  require('./modle/user_model') 

// 路由---------------------------------------------------------------------
// app.all("*",(req,res)=>{
//   console.log('这里？',req.url,req.body);
//   res.send('ok')
// })
//查询全部用户信息
app.get("/users",async(req,res)=>{
 await users.
  findAll().then(val=>{
      res.send({
          message:'GET:Success',
          code:200, 
          data:val
      })   
  })
})
// 注册用户 
app.post("/users/register",async (req,res)=>{
  console.log(req.body);
  if (req.body.password == undefined) {
    return res.send({
      message:'required password',
      code:400
    });
  }else{
    req.body.password = bcryptjs.hashSync(req.body.password, 8);//加密密码
  }
  req.body.id = require('node-uuid')().replace(/-/g, '')//设置uuid，去除横线-,
 await users.
  create(req.body).then(val=>{
      res.send({
          message:'Register:Success',
          code:200, 
          data:val 
      })  
  }).catch(err=>{
    console.log(err);
    if (err.errors[0].type == 'unique violation') {
        res.send({
          message:`${req.body.email} exist!`,
          code:400, 
          error:err.errors[0].type
        })
    }else{
      res.send({
        message:'Server is wrong',
        code:500, 
        error:err.errors[0].type
      })
    }
  })
})

// 用户登录
app.post("/users/login",async (req,res)=>{
  console.log(req.body); 
  // res.send('ok')
  await users.findOne({where:{email:req.body.email}}).then(val=>{
    console.log(val);
   if (val == undefined) {
      res.send({
        code:404,
        message:'User don`t exist',
      })
   }
   if (bcryptjs.compareSync(req.body.password, val.password) == false) {
      res.send({
        code:401,
        message:'Password is wrong', 
      })
   }else{
      res.send({
        code:200,
        message:'Login:Success',
        data:{
          token:jwt.sign({id:val.id},Secret,{expiresIn:'1h'}),
          userInfo:val,
        }
      })
   }

  }).catch(err=>{
    res.send({
      message:'Server is wrong',
      code:500,
      error:err
  })
})
});
// 更新用户信息
app.put("/users/update",async (req,res)=>{
  if (req.headers.authorization == undefined) {
    return res.send({
      code:401,
      message:'Please take your token',
    })
  }
  jwt.verify(req.headers.authorization,Secret,async (err,decoded)=>{
    if (err) {
      return res.send({
        code:401,
        message:'Token is wrong',
      })
    }else{
      req.body.id = decoded.id;
    }
  })
  // console.log(req.body);
  await users.update(req.body,{where:{id:req.body.id}})
  .then(async val=>{
    if (val == 1) {
      // back resource
     await users.findOne({where:{id:req.body.id}})
      .then(val1=>{
        res.send({
          code:200,
          message:'Update:Success',
          data:val1,
        })
      })
      
    }else{
      res.send({
        code:400,
        message:'Update:Failed',
      })
    }
  }).catch(err=>{
    res.send({
      message:'Server is wrong',
      code:500,
      error:err
  })
})
})

// 删除用户
app.delete("/users/delete",async (req,res)=>{
  if (req.headers.authorization == undefined) {
    return res.send({
      code:401,
      message:'Please take your token',
    })
  }
  jwt.verify(req.headers.authorization,Secret,async (err,decoded)=>{
    if (err) {
      return res.send({
        code:401,
        message:'Token is wrong',
      })
    }else{
      req.body.id = decoded.id;
    }
  })

  await users.findOne({where:{id:req.body.id}}).then(val =>{
      val.destroy()
      val.save()
      res.send({
        message:'Delete:Success',
        code:200,
      })
  }).catch(err=>{
    res.send({
      message:'Server is wrong',
      code:500,
      error:err
  })
  })
})



app.listen(port, () => {
  console.log(`Server is running at http://localhost:${port}`);
}); 
